package com.xyz.springcloud.Util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author 肖咉卓
 */
@Slf4j
@Component
public class IdGeneratorSnowflake {
    /**
     * 几号机房
     */
    private long workerId = 0;
    /**
     * 几号机器
     */
    private long datacenterId = 1;
    private Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);

    /**
     * @PostConstruct 该注解用于加载时执行
     */
    @PostConstruct
    public void init(){
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workerId："+workerId);
        }catch (Exception e){
            e.printStackTrace();
            log.info("当前机器的workerId：获取失败"+e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowflakeId(){
        //获得id
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId,long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);
        //获得id
        return snowflake.nextId();
    }

}
